<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
         <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>商品管理</el-breadcrumb-item>
         <el-breadcrumb-item>添加商品</el-breadcrumb-item>
       </el-breadcrumb>

       <el-card>
          <el-alert
             title="添加商品信息"
             type="info"
             center
             show-icon
             :closable="false"
             >
           </el-alert>

           <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
             <el-step title="基本信息"></el-step>
             <el-step title="商品参数"></el-step>
             <el-step title="商品属性"></el-step>
             <el-step title="商品图片"></el-step>
             <el-step title="完成"></el-step>
           </el-steps>

<el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px" label-position="top">
            <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
               <el-tab-pane label="基本信息" name= '0'>
                 <el-form-item label="商品名称" prop="goods_Name">
                   <el-input v-model="addFrom.goods_Name"></el-input>
                 </el-form-item>
                 <el-form-item label="商品价格" prop="goods_Price">
                   <el-input v-model="addFrom.goods_Price" type="number"></el-input>
                 </el-form-item>
                 <el-form-item label="商品数量" prop="goods_Number">
                   <el-input v-model="addFrom.goods_Number" type="number"></el-input>
                 </el-form-item>
                 <el-form-item label="商品分类" prop="goods_Cat">
                   <el-cascader v-model="addFrom.goods_Cat" :options="cateList" :props="{ expandTrigger:'hover',value:'cat_Id',label:'cat_Name',children:'children'}"
                     @change="handleChange" clearable change-on-select></el-cascader>
                 </el-form-item>
               </el-tab-pane>
               <el-tab-pane label="商品参数" name='1'>
                 <el-form-item :label="item.propertyName" v-for="item in mnayTableData" :key="item.id">
                    <el-checkbox-group v-model="item.value">
                       <el-checkbox :label="cb" v-for="(cb,i) in item.value" :key="i" border></el-checkbox>
                     </el-checkbox-group>
                 </el-form-item>
               </el-tab-pane>
               <el-tab-pane label="商品属性" name='2'>
                 <el-form-item :label="item.propertyName" v-for="item in onlyTableData" :key="item.id">
                   <el-select v-model="item.selectValue">
                     <el-option v-for="(otem,index) in item.value" :key="index" :label="otem" :value="otem"></el-option>
                   </el-select>
                 </el-form-item>
               </el-tab-pane>
               <el-tab-pane label="商品图片" name='3'>
                 <el-upload
                   action="https://localhost:44331/api/Goods/File"
                   :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   :headers="headerobj"
                   list-type="picture-card"
                   :on-success="handleSuccess"
                   >
                   <el-button size="small" type="primary">点击上传</el-button>
                   <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                 </el-upload>
                 <el-button class="btn1" type="primary" size="small" v-on:click="add">添加商品</el-button>
               </el-tab-pane>
             </el-tabs>
</el-form>
       </el-card>
  </div>
</template>

<script>
  export default{
    data(){
      return{
        activeIndex:'0',
        addFrom:{
          goods_Name:'',
          goods_Price:0,
          goods_Number:0,
          goods_Cat:[],
          goodsPictures:[],
          goodsInformations:[]
        },
        addFromRules:{
          goods_Name:[
            {required:true,message:'请输入商品名称',trigger:'blur'}
          ],
          goods_Price:[
            {required:true,message:'请输入商品价格',trigger:'blur'}
          ],
          goods_Number:[
            {required:true,message:'请输入商品数量',trigger:'blur'}
          ],
          goods_Cat:[
            {required:true,message:'请选择分类',trigger:'blur'}
          ]
        },
        cateList:[],
        mnayTableData:[],
        onlyTableData:[],
        headerobj:{
          Authorization:window.sessionStorage.getItem('token')
        },
        uploadURL:'https://localhost:44331/api/Goods/File'
      }
    },
    created(){
 this.getCateList()
    },
    methods:{
     async getCateList(){
      const{data:res}= await this.$http.get("https://localhost:44331/api/Commodity")
       if (res.status !== 200) {
         return this.$message.error('获取数据失败')
       }
       this.cateList=this.getTreeData(res.data.data)
      },
      getTreeData(data) {
                      // 循环遍历json数据
                      for (var i = 0; i < data.length; i++) {

                          if (data[i].children.length < 1) {
                              // children若为空数组，则将children设为undefined
                              data[i].children = undefined;
                          } else {
                              // children若不为空数组，则继续 递归调用 本方法
                              this.getTreeData(data[i].children);
                          }
                      }
                      return data;
                  },
                  handleChange(){
                    if(this.addFrom.goods_Cat.length!==3){
                      this.addFrom.goods_Cat=[]
                    }
                  },
                  beforeTabLeave(activeName,oldActiveName){
                    if(oldActiveName==='0'&&this.addFrom.goods_Cat.length!==3){
                      return false
                    }
                  },
                 async tabClicked(){
                    if(this.activeIndex==='1'){
                   const{data:res} = await this.$http.get("https://localhost:44331/api/Categories",{params:{id:this.cateId,state:1}})
                   if (res.status !== 200) {
                     return this.$message.error('获取动态参数列表失败')
                   }
                   this.mnayTableData=res.data
                    }
                    else if(this.activeIndex==='2'){
                      const{data:res} = await this.$http.get("https://localhost:44331/api/Categories",{params:{id:this.cateId,state:0}})
                      if (res.status !== 200) {
                        return this.$message.error('获取静态数据失败')
                      }
                      res.data.forEach(item=>{
                        item.selectValue=[]
                      })
                      this.onlyTableData=res.data
                      console.log(this.onlyTableData)

                    }
                  },
                  handlePreview(){

                  },
                 async handleRemove(file){
                    const filePath=file.response.data
                   const i =this.addFrom.goodsPictures.findIndex(x=>x===filePath)
                   this.addFrom.goodsPictures.splice(i,1)

                const{data:res} = await this.$http.delete("https://localhost:44331/api/Goods/File/"+filePath)
                if (res.status !== 200) {
                  return this.$message.error('删除失败')
                }
                this.$message.success("删除成功 ")

                  },
                  handleSuccess(response){
                    const picInfo=response.data
                    this.addFrom.goodsPictures.push(picInfo)

                  },
                  add(){
                    this.$refs.addFromRef.validate(async valid=>{
                      if(!valid){
                        return this.$message.error("请填写必要的表单项")
                      }
                      this.addFrom.goods_Cat=this.addFrom.goods_Cat[2]
                      this.addFrom.goodsPictures
                      this.mnayTableData.forEach(item=>{
                        if(item.value.length<1){
                          item.value = undefined;
                          return
                        }
                        const newInfo={propertyName:item.propertyName,value:item.value.join(","),state:0}
                        this.addFrom.goodsInformations.push(newInfo)
                      })
                      this.onlyTableData.forEach(item=>{
                        if(item.selectValue.length<1){
                          item.selectValue = undefined;
                          return
                        }
                        const newInfo={propertyName:item.propertyName,value:item.selectValue,state:1}
                         this.addFrom.goodsInformations.push(newInfo)
                        })

                    const{data:res}=await this.$http.post("https://localhost:44331/api/Goods",this.addFrom)
                    if (res.status !== 200) {
                      return this.$message.error('添加商品失败')
                    }
                    this.$message.success("添加成功")
                    this.$router.replace("/list")

                    })
                  }
    },
    computed:{
      cateId(){
        if(this.addFrom.goods_Cat.length===3){
          return this.addFrom.goods_Cat[2]
        }
        return null
      }

    }

  }
</script>

<style style="less" scoped>
  .el-checkbox{
    margin: 0 10px 0 0 !important;
  }
  .btn1{
    margin-left: ;
    margin-right: auto;
    margin-top: 100px;
  }
</style>
